﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gfw.Models.Account;
using Gfw.Repository;
using NHibernate.Criterion;

namespace Gfw.Repositories.Account
{
    public class ActUserWarrantRepository : Repository<ActUserWarrant>
    {
        #region Const Fields

        private const int PROGRESS = 0;
        private const int TRANSFER = 1;

        #endregion


        /// <summary>
        /// 根据双方用户ID与交易日期和状态查询担保交易记录
        /// </summary>
        /// <param name="userID">转出用户ID</param>
        /// <param name="toUserID">转入用户ID</param>
        /// <param name="tradeDate">担保日期</param>
        /// <param name="status">担保状态</param>
        /// <param name="unitOfWork"></param>
        /// <returns></returns>
        public ActUserWarrant GetWarrantByBothUserIDAndTradeDate(string userID,
            string toUserID, DateTime tradeDate, int status = int.MinValue, UnitOfWork unitOfWork = null)
        {
            if (unitOfWork == null)
            {
                var query = Session.CreateCriteria("ActUserWarrant").Add(Expression.Eq("Userid", userID))
                    .Add(Expression.Eq("ToUserId", toUserID)).Add(Expression.Eq("TradeDate", tradeDate));

                if (status != int.MinValue)
                    query = query.Add(Expression.Eq("Status", status));

                return query.List<ActUserWarrant>().FirstOrDefault();
            }
            else
            {
                var query = unitOfWork.Session.CreateCriteria("ActUserWarrant").Add(Expression.Eq("Userid", userID))
                    .Add(Expression.Eq("ToUserId", toUserID)).Add(Expression.Eq("TradeDate", tradeDate));

                if (status != int.MinValue)
                    query = query.Add(Expression.Eq("Status", status));

                return query.List<ActUserWarrant>().FirstOrDefault();
            }
        }


        public virtual IList<ActUserWarrant> Query(string userId, int status, DateTime? start, DateTime? end, int pageIndex, int pageSize, out int totalPage)
        {
            var query = Session.CreateCriteria("ActUserWarrant");
            ICriterion ic = Expression.Or(Expression.Eq("Userid", userId), Expression.Eq("ToUserId", userId));
            query = query.Add(ic);

            if (start.HasValue)
                query = query.Add(Expression.Ge("TradeDate", start.Value));
            if (end.HasValue)
            {
                end = end.Value.AddDays(1);
                query = query.Add(Expression.Le("TradeDate", end.Value));
            }

            if (status != int.MinValue)
                query = query.Add(Expression.Eq("Status", status));

            query = query.AddOrder(new Order("TradeDate", false));
            totalPage = (query.List().Count + pageSize - 1) / pageSize;

            return query.SetFirstResult(pageIndex * pageSize).SetMaxResults(pageSize).List<ActUserWarrant>();
        }


        /// <summary>
        /// 用于查询担保交易过期（5天）记录，返还给卖家
        /// <para>系统自动运行</para>
        /// </summary>
        /// <returns></returns>
        public IList<ActUserWarrant> Query()
        {
            DateTime deadLine = DateTime.Now.AddDays(-5);
            var query = Session.CreateQuery("from ActUserWarrant where " +
                "(TradeDate<=:deadLine and Status=:progress) or (TradeDate<=:deadLine and Status=:transfer)")
                .SetDateTime("deadLine", deadLine)
                .SetInt32("progress", PROGRESS)
                .SetInt32("transfer", TRANSFER);

            return query.List<ActUserWarrant>();
        }
    }
}
